package com.jeesite.modules.fl.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.fl.entity.Clinic;
import com.jeesite.modules.fl.entity.Doctor;
import com.jeesite.modules.fl.service.ClinicService;
import com.jeesite.modules.fl.service.DoctorService;
import com.jeesite.modules.sys.entity.DictData;
import com.jeesite.modules.sys.utils.DictUtils;


@Controller
@RequestMapping(value = "${adminPath}/fl/doctor")
public class DoctorController extends BaseController{
	
	@Autowired
	private DoctorService doctorService;
	@Autowired
	private ClinicService clinicService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Doctor get(String id, boolean isNewRecord) {
		return doctorService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("fl:doctor:view")
	@RequestMapping(value = {"list", ""})
	public String list(Doctor doctor, HttpServletRequest request, HttpServletResponse response, Model model) {
		Clinic entity = new Clinic();
		entity.setStatus("0");
		List<Clinic> clinicList = clinicService.findList(entity);
		model.addAttribute("doctor", doctor);
		List<DictData> dicts = new ArrayList<DictData>();
        for(Clinic c:clinicList){
        	DictData data = new DictData();
        	data.setDictLabelOrig(c.getName());
        	data.setDictValue(c.getId());
        	dicts.add(data);
        }
		model.addAttribute("clinicList", dicts);
		return "modules/fl/doctorList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("fl:doctor:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Doctor> listData(Doctor doctor, HttpServletRequest request, HttpServletResponse response) {
		Page<Doctor> page = doctorService.findPage(new Page<Doctor>(request, response), doctor);
		return page;
	}
	
	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("fl:doctor:view")
	@RequestMapping(value = "form")
	public String form(Doctor doctor, Model model) {
		Clinic entity = new Clinic();
		entity.setStatus("0");
		List<Clinic> clinicList = clinicService.findList(entity);
		model.addAttribute("doctor", doctor);
		model.addAttribute("clinicList", clinicList);
		List<DictData> departmentList = DictUtils.getDictList("fl_department");
        List<DictData> nowList = departmentList;
        if(doctor.getClinics() != null && !doctor.getClinics().isEmpty()){
        	StringBuilder sb = new StringBuilder();
        	for(String id : doctor.getClinics().split(",")){
        		Clinic clinic = clinicService.get(id);
        		sb.append(clinic.getDepartments()).append(",");
        	}
        	nowList = new ArrayList<DictData>();
        	for(DictData data : departmentList){
        		if(sb.toString().contains(data.getDictValue())){
        			nowList.add(data);
        		}
        	}
        }
		model.addAttribute("departmentList", departmentList);
		model.addAttribute("nowList", nowList);
		return "modules/fl/doctorForm";
	}
	
	@ResponseBody
	@RequiresPermissions("fl:doctor:edit")
	@RequestMapping(value = "departmentList")
	public List<DictData> departmentList(String clinics) {
		List<DictData> departmentList = DictUtils.getDictList("fl_department");
		StringBuilder sb = new StringBuilder();
    	for(String id : clinics.split(",")){
    		Clinic clinic = clinicService.get(id);
    		sb.append(clinic.getDepartments()).append(",");
    	}
    	List<DictData> nowList = new ArrayList<DictData>();
    	for(DictData data : departmentList){
    		if(sb.toString().contains(data.getDictValue())){
    			nowList.add(data);
    		}
    	}
		return nowList;
	}
	
	/**
	 * 验证名称是否有效
	 * @param oldDoctorName
	 * @param name
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("fl:doctor:edit")
	@RequestMapping(value = "checkDoctorName")
	public String checkDoctorName(String oldDoctorName, String name) {
		if (name !=null && name.equals(oldDoctorName)) {
			return "true";
		} else if (name !=null && doctorService.getByName(name) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("fl:doctor:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Doctor doctor) {
		doctorService.save(doctor);
		return renderResult(Global.TRUE, text("保存数据成功！"));
	}
	
	/**
	 * 停用数据
	 */
	@RequiresPermissions("fl:doctor:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(Doctor doctor) {
		doctor.setStatus(Doctor.STATUS_DISABLE);
		doctorService.updateStatus(doctor);
		return renderResult(Global.TRUE, text("停用数据成功"));
	}
	
	/**
	 * 启用数据
	 */
	@RequiresPermissions("fl:doctor:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(Doctor doctor) {
		doctor.setStatus(Doctor.STATUS_NORMAL);
		doctorService.updateStatus(doctor);
		return renderResult(Global.TRUE, text("启用数据成功"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("fl:doctor:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Doctor doctor) {
		doctorService.delete(doctor);
		return renderResult(Global.TRUE, text("删除数据成功！"));
	}
	
	@RequestMapping(value = "import/doctorTemplate")
	public void importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		ExcelExport ee = new ExcelExport("医师数据", Doctor.class);
		try {
			String fileName = "医师数据导入模板.xlsx";
			List<Doctor> list = new ArrayList<Doctor>();
			ee.setDataList(list).write(response, fileName).close();
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		} finally{
			ee.close();
		}
	}
	
	@RequestMapping(value = "export", method=RequestMethod.POST)
    public void exportFile(Doctor doctor, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		ExcelExport ee = new ExcelExport("医师数据", Doctor.class);
		try {
            String fileName = "医师数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; 	
            List<Doctor> list = doctorService.findList(doctor);
    		ee.setDataList(list).write(response, fileName);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出医师失败！失败信息："+e.getMessage());
		} finally{
			ee.close();
		}
    }
    
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importData(MultipartFile file, String updateSupport)
    {
        String message;
        boolean isUpdateSupport = "1".equals(updateSupport);
        try{
	        message = doctorService.importData(file, Boolean.valueOf(isUpdateSupport));
	        return renderResult("true", (new StringBuilder()).append("posfull:").append(message).toString());
        }catch(Exception ex){
        	return renderResult("false", (new StringBuilder()).append("posfull:").append(ex.getMessage()).toString());
        }
    }
}
